import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2023-02-06
 * Time: 20:48
 */
public class JDBCdemo {
    public static void main(String[] args) throws SQLException {
        //1.先创建DataSource数据源,描述mysql数据库在哪
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/wyz?characterEncoding=utf8&useSSl=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("Wyz20030404");
        //2.和数据库建立连接
        Connection connection = dataSource.getConnection();
        //通过控制台.来输入用户信息
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入学号: ");
        int id = scanner.nextInt();
        System.out.println("请输入姓名: ");
        String name = scanner.next();

        String sql = "insert into stu values(?,?)";
        //jdbc中还需要搭配一个特定的对象,来描述这里的sql的情况
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.setString(2,name);
        System.out.println("sql :"+statement);
        //4.执行SQL,针对增,删,改,使用executeUpdate来执行
        //针对查,使用executQuery来执行
        //返回结果的含义是,这个操作影响到几行
        int ret = statement.executeUpdate();
        System.out.println("ret = "+ ret);
        //5.断开连接,释放资源
        statement.close();
        connection.close();
    }
}
